<template>
  <div class="flex flex-col h-full p-3">
    <div class="flex-shrink-0 flex flex-row items-center justify-between">
      <h2 class="text-3xl">
        API列表 <small class="text-lg">{{ projectName }}</small>
      </h2>
      <div>
        <a-space>
          <a-button size="small" @click="onBack">返回</a-button>
          <a-button size="small" type="primary" @click="onAdd">新增</a-button>
          <a-input v-model:value="kw" placeholder="输入关键词查询..." @press-enter="onChange" />
        </a-space>
      </div>
    </div>
    <div class="flex-1 h-0 pt-3">
      <vxe-grid v-bind="gridOptions" :data="tablePage.list" :loading="loading">
        <template #name="{ data, rowIndex }">
          <span :class="[{ 'text-green-600': data[rowIndex].enable }]">{{ data[rowIndex].name }}</span>
        </template>
        <template #enable="{ data, rowIndex }">
          {{ data[rowIndex].enable === 1 ? '是' : '否' }}
        </template>
        <template #createdAt="{ data, rowIndex }">
          {{ dateFormat(data[rowIndex].createdAt) }}
        </template>
        <template #updatedAt="{ data, rowIndex }">
          {{ dateFormat(data[rowIndex].updatedAt) }}
        </template>
        <template #operate="{ data, rowIndex }">
          <a-space>
            <a-button type="text" size="small" @click="() => onEdit(data[rowIndex])">编辑</a-button>
            <a-button type="text" size="small" @click="() => onEditMockMethod(data[rowIndex])">自定义mock</a-button>
            <a-button type="text" size="small" @click="() => onOpenCopyModal(data[rowIndex])">复制URL</a-button>
            <a-button type="text" size="small" @click="() => onCopyAdd(data[rowIndex])">复制并新建</a-button>
            <a-popconfirm
              title="确认删除？"
              ok-text="是"
              cancel-text="否"
              placement="leftTop"
              @confirm="() => onDel(data[rowIndex])"
            >
              <a-button type="text" size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
        <template #pager>
          <!--使用 pager 插槽-->
          <vxe-pager
            :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            v-model:current-page="tablePage.current"
            v-model:page-size="tablePage.size"
            :total="tablePage.total"
            @page-change="onPageChange"
          >
          </vxe-pager>
        </template>
      </vxe-grid>
      <AddEditModal ref="AddEditModalRef" @saveSuc="onAddSuc" @editSuc="onUpdateSuc"></AddEditModal>
      <MockMethodEditorDrawer
        ref="MockMethodEditorDrawerRef"
        @methodContentSaveSuc="onMethodContentSaveSuc"
      ></MockMethodEditorDrawer>
      <MockApiUrlCopyModal
        v-model="copyModalVisible"
        :apiInfo="copyUrlApiInfo"
        :projectFlag="projectFlag"
      ></MockApiUrlCopyModal>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import AddEditModal from './AddEditModal.vue'
import MockMethodEditorDrawer from './MockMethodEditorDrawer.vue'
import MockApiUrlCopyModal from './MockApiUrlCopyModal.vue'
import { useRequest } from 'vue-request'
import { copyAdd, page, remove } from '@render/service/FrontApiService'
import { iso8061DatetimeStrFormat } from '@render/util/DateUtil'
import type { ComponentExposed } from 'vue-component-type-helpers'
import { message } from 'ant-design-vue'

type AddEditModalExpose = ComponentExposed<typeof AddEditModal>
type MockMethodEditorDrawerExpose = ComponentExposed<typeof MockMethodEditorDrawer>
const AddEditModalRef = ref<AddEditModalExpose>()
const MockMethodEditorDrawerRef = ref<MockMethodEditorDrawerExpose>()
const copyModalVisible = ref(false)
const copyUrlApiInfo = ref<ApiInfo>()
const $route = useRoute()
const $router = useRouter()

const kw = ref('')
const projectId = computed(() => parseInt($route.params.projectId as string))
const projectName = computed(() => $route.query.projectName)
const projectFlag = computed<string>(() => $route.query.projectFlag as string)
const {
  run,
  data: tablePage,
  loading,
} = useRequest(page, {
  manual: true,
  initialData: { current: 1, list: [], size: 15, total: 0 },
})
run(projectId.value, 1, 15, kw.value)

const { run: runRemove } = useRequest(remove, {
  manual: true,
})
const gridOptions = reactive<VxeGridProps<ApiInfo>>({
  border: false,
  height: 'auto',
  columnConfig: {
    resizable: true,
  },
  /**
   * 表格数据默认为空
   */
  data: [],
  columns: [
    { type: 'seq', width: 50 },
    { field: 'id', visible: false },
    { field: 'name', title: '名称', minWidth: 200, showOverflow: true, slots: { default: 'name' } },
    { field: 'method', title: '请求方式', width: 80 },
    { field: 'uri', title: '请求URI', minWidth: 300, showOverflow: true },
    { field: 'enable', title: '启用', width: 60, slots: { default: 'enable' } },
    { field: 'createdAt', title: '创建日期', width: 150, slots: { default: 'createdAt' } },
    { field: 'updatedAt', title: '更新日期', width: 150, slots: { default: 'updatedAt' } },
    { title: '操作', width: 380, slots: { default: 'operate' }, fixed: 'right' },
  ],
})
/**
 * 分页事件监听: 分页大小改变, 页号改变，都会触发该事件
 *
 * @param currentPage 当前页码
 * @param pageSize 每页显示记录数
 */
const onPageChange = ({ currentPage, pageSize }) => {
  run(projectId.value, currentPage, pageSize, kw.value)
}

function onChange() {
  run(projectId.value, 1, tablePage.value.size, kw.value)
}
function onAdd() {
  AddEditModalRef.value?.openModal('新增', projectId.value)
}
async function onDel(rowData) {
  await runRemove(rowData.id)
  run(projectId.value, tablePage.value.current, tablePage.value.size, kw.value)
}
function onEdit(rowData: ApiInfo) {
  AddEditModalRef.value?.openModal('新增', projectId.value, rowData)
}
function onEditMockMethod(rowData: ApiInfo) {
  MockMethodEditorDrawerRef.value?.openDrawer(rowData)
}
function onBack() {
  $router.push({ name: 'ProjectPage' })
}
function onAddSuc() {
  run(projectId.value, 1, 15, kw.value)
}
function onUpdateSuc() {
  run(projectId.value, tablePage.value.current, 15, kw.value)
}
function onMethodContentSaveSuc(d: ApiInfo) {
  run(projectId.value, tablePage.value.current, tablePage.value.size, kw.value)
}
function dateFormat(iso8061DatetimeStr?: string) {
  if (iso8061DatetimeStr) {
    return iso8061DatetimeStrFormat(iso8061DatetimeStr)
  }
  return ''
}
function onOpenCopyModal(rowData: ApiInfo) {
  copyModalVisible.value = true
  copyUrlApiInfo.value = rowData
}
async function onCopyAdd(rowData: ApiInfo) {
  await copyAdd(rowData.id)
  run(projectId.value, 1, tablePage.value.size, kw.value)
  message.success('操作成功')
}
</script>

<style scoped></style>
